﻿using PayrollHR.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using OfficeOpenXml;
using Payroll.Common.Utils;
using Payroll.BusinessLogic.Package;
using Payroll.BusinessLogic;
using OfficeOpenXml.Style;
using OfficeOpenXml.DataValidation;

namespace PayrollHR.Administration.Modules
{
    public partial class PackagePriceControl : BasePayrollAdministrationUserControl
    {
        private const int m_pageSize = int.MaxValue;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Bind();
            }
        }
        protected void Bind()
        {
            var items = PackagePriceSearch1.GetPackageSearch();
            List<PackagePrice> package = this.PackageService.GetAllPackagePrice(items, m_pageSize);
            gvPackage.DataSource = package;
            gvPackage.DataBind();
        }
        protected void Delete()
        {
            string PackagePricesID = "";
            foreach (GridViewRow row in gvPackage.Rows)
            {
                var cbPackagePricesID = row.FindControl("cbPackagePricesID") as CheckBox;

                bool isChecked = cbPackagePricesID.Checked;
                if (isChecked)
                {
                    PackagePricesID += gvPackage.DataKeys[row.RowIndex].Value + ",";
                }
            }
            if (PackagePricesID.Length > 0)
            {
                PackagePricesID = PackagePricesID.TrimEnd(',');
                this.PackageService.Delete(packagePricesID: PackagePricesID);
                this.Bind();
            }
        }
        protected void SearchButton_Click(object sender, EventArgs e)
        {
            Bind();
        }
        protected void Border(ExcelWorksheet worksheet, int row, int Colfrom, int ColTo)
        {
            for (int i = Colfrom; i <= ColTo; i++)
            {
                var cell = worksheet.Cells[row, i];
                var border = cell.Style.Border;
                border.Bottom.Style =
                    border.Top.Style =
                    border.Left.Style =
                    border.Right.Style = ExcelBorderStyle.Thin;
            }
        }
        protected void WriteSheets(FileInfo filewrite, List<Package> List)
        {
            int MaxRow = List.Count;
            using (var xlsx = new ExcelPackage(filewrite))
            {
                ExcelWorksheet worksheet = xlsx.Workbook.Worksheets[1];
                if (MaxRow > 3)
                {
                    worksheet.InsertRow(3, MaxRow - 3, 2);
                    int i = 2;
                    foreach (var info in List)
                    {
                        worksheet.Cells[i, 1].Value = i - 2;
                        worksheet.Cells[i, 2].Value = info.PackCode;
                        worksheet.Cells[i, 3].Value = info.Name;
                        worksheet.Cells[i, 4].Value = info.PackTime;
                        worksheet.Cells[i, 5].Value = info.PackTypeName;
                        this.Border(worksheet, i, 1, 7);
                        i += 1;
                    }
                }
                xlsx.Save();
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                this.Delete();
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }
        protected void gvPackage_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvPackage.PageIndex = e.NewPageIndex;
            Bind();
        }
        protected void btnInport_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                string fileName = fileUpload.PostedFile.FileName;
                string fileExtension = System.IO.Path.GetExtension(fileName);
                string[] matchExtension = { ".xls", ".xlsx" };
                if (matchExtension.Contains(fileExtension))
                {
                    fileUpload.SaveAs(Server.MapPath(@"..\Files\" + fileName));
                    FileInfo template = new FileInfo(Server.MapPath(@"..\Files\" + fileName));
                    using (var PackagePrice = new ExcelPackage(template))
                    {
                        ExcelWorkbook workbook = PackagePrice.Workbook;
                        if (workbook != null)
                        {
                            if (workbook.Worksheets.Count > 0)
                            {
                                ExcelWorksheet currentWorksheet = workbook.Worksheets.First();
                                List<PackagePrice> List = new List<PackagePrice>();
                                this.ReadSheets(ref List, currentWorksheet);
                                if (List.Count > 0)
                                {
                                    this.PackageService.SavePackagePrice(List);
                                }
                            }
                            Bind();
                        }
                    }
                    File.Delete(Server.MapPath(@"..\Files\" + fileName));
                }
            }
        }
        protected void ReadSheets(ref List<PackagePrice> List, ExcelWorksheet worksheet)
        {
            int rowStart = 2;
            int breaks = 0;
            string packageCode = "";
            string DateApply = "";
            object price = null;
            DateTime isdate;
            while (true)
            {
                packageCode = CommonHelper.ToString(worksheet.Cells[rowStart, 2].Value);
                DateApply = CommonHelper.ToString(worksheet.Cells[rowStart, 6].Value);
                price = CommonHelper.ToDec(worksheet.Cells[rowStart, 7].Value);
                if (packageCode.Length > 0 && DateApply.Length > 0 && CommonHelper.ToDate(DateApply, out isdate))
                {
                    List.Add(new PackagePrice { PackCode = packageCode, DateApply = isdate.ToString("yyyy-MM-dd"), Price = CommonHelper.ToString(price) });
                }
                else
                    breaks += 1;
                if (breaks > 2)
                    break;

                rowStart += 1;
            }


        }
        protected void gvPackage_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblPrice = e.Row.FindControl("lblPrice") as Label;
                lblPrice.Text = String.Format("{0:#,###0}", CommonHelper.ToDec(lblPrice.Text));
            }
        }

        protected void ExportButton_Click(object sender, EventArgs e)
        {
            string fileName = string.Format("Mau_import_bang_gia_{0}", DateTime.Now.ToString("dd-MM-yyyy_HH.mm") + ".xlsx");
            string fileInfo = Server.MapPath(@"..\Administration\FileExport\" + fileName);

            FileInfo template = new FileInfo(Server.MapPath(@"..\Administration\Template\Template_import_gia.xlsx"));
            FileInfo filewrite = template.CopyTo(fileInfo, true);
            var search = new PackageSearch { PackName = null, PackType = null };
            var packageColection = this.PackageService.GetAllPackage(search, 100);
            WriteSheets(filewrite, packageColection);
            hlexport.Visible = true;
            hlexport.Text = "Save As File Export";
            hlexport.NavigateUrl = "../FileExport/" + fileName;
        }
    }
}